<?php

class SubjectService extends ServiceAbstract {
	
	private $_mapper;

	public function __construct(){
		$this->_mapper = new Db_Mapper_Subject();
	}
	
	/**
	 * Vrtáti vsetky predmety
	 * 
	 * @return array
	 */
	public function fetchAll(){
		$order = $this->_mapper->getTable()->select()->order("name");
		return $this->_mapper->getTable()->fetchAll($order)->toArray();
	}
	
	/**
	 * Vrati vsetky predmety patriace danemu oboru
	 * 
	 * @param integer $IDoboru
	 * 
	 * @return array|boolean
	 */
	public function fetchSubjectsByIdOboru($IDoboru){
		$id = (int)$IDoboru;
		
		if($id == 0){
			return false;
		}
		
		$select = $this->_mapper->getTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
		$select->setIntegrityCheck(false)
		->where('subject_st_obory.Id_oboru = ?',$id)		
		->join('subject_st_obory','subject_st_obory.sid = subject.sid',array())
		->order('subject.name');
				
		return $this->_mapper->getTable()->fetchAll($select)->toArray();
	}
	
	
	/**
	 * Vrati vsetky predmety, ktore ma student priradene v ramci svojho oboru resp. triedy
	 
	 * @param integer $IDst
	 * 
	 * @return array|boolean
	 */
	public function fetchSubjectsByIDStudenta($IDst){
		$idStudenta = (int)$IDst;
		
		if($IDst == 0){
			return false;
		}
		
		/*
		 * Zisti id oboru
		 */
		$studentMapper = new Db_Mapper_Student();
		$select = $studentMapper->getTable()->select(Zend_Db_Table::SELECT_WITHOUT_FROM_PART);
		$select->setIntegrityCheck(false)
		->from('Student',array())
		->join('Student_has_Tridy','Student_has_Tridy.Student_ID_st=Student.ID_st',array())
		->join('T_Tridy','T_Tridy.ID_tr=Student_has_Tridy.Tridy_ID_tr',array())
		->join('St_obory','St_obory.Id_oboru=T_Tridy.Id_oboru',array('Id_oboru'))
		->where('Student.ID_st = ?',$idStudenta);
				
		$IDOboru = $studentMapper->getTable()->fetchAll($select)->current()->Id_oboru;		
		
		$select = $this->_mapper->getTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
		$select->setIntegrityCheck(false)
		->join('subject_st_obory','subject_st_obory.sid=subject.sid',array())
		->where('subject_st_obory.Id_oboru = ?',$IDOboru)
		->order('subject.name');
		
		return $this->_mapper->getTable()->fetchAll($select)->toArray();
	}
	
	
	/**
	 * Odstrani pridelenie predmetu pre dany obor
	 * 
	 * @param integer $sid
	 * @param integer $idOboru
	 * 
	 * @return boolean
	 */
	public function deleteSubjectFromObor($sid,$idOboru){
		
		$idOboru = (int)$idOboru;
		$sid = (int)$sid;
		
		if($sid == 0 || $idOboru == 0){
			return false;
		}

		$result = $this->_mapper->getTable()->getAdapter()->query(
						'DELETE FROM subject_st_obory WHERE sid = ? AND Id_oboru = ?',
						array($sid,$idOboru)
		);	
		
		
		return ($result->rowCount() > 0) ? true : false;
	}
}

?>